﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Com.Common.Cms
{
   public enum FileCode
    {
         jpg = 255216,
         gif  = 7173 ,
         bmp = 6677,
         png  = 13780,
         exe  = 7790,
         rar  = 8297,

         xlsx = 8075,
         xls = 208207
    }
   public sealed class FileType
    {
       public static String GetFileType(System.IO.Stream stream)
       {
           int code = GetFileCode(stream);
           String fileType = GetFileType(code);
           return fileType;
       }


       private static string GetFileType(int code)
       {
           switch (code)
           {
               case (int)FileCode.bmp:
                   return ".bmp";
               case (int)FileCode.exe:
                   return ".exe";
               case (int)FileCode.gif:
                   return ".gif";
               case (int)FileCode.jpg:
                   return ".jpg";
               case (int)FileCode.png:
                   return ".png";
               case (int)FileCode.rar:
                   return ".rar";
               case (int)FileCode.xls:
                   return ".xls";
               case(int)FileCode.xlsx:
                   return ".xlsx";
               default:
                   return "unknow";
           }
       }

       private static int GetFileCode(System.IO.Stream stream)
       {
           byte[] FileContent = new byte [stream.Length];
           stream.Read(FileContent, 0, (int)stream.Length);
           System.IO.MemoryStream ms = new System.IO.MemoryStream(FileContent);
           System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
           StringBuilder code = new StringBuilder();
           byte [] buf= new byte[2];
           buf = br.ReadBytes(2);
           foreach (byte b in buf)
           {
               code.Append(b.ToString());
           }
           int result = 0;
           if (Int32.TryParse(code.ToString(), out result))
           {
               return result;
           }
           else
           {
               return -1;
           }
       }
    }
}
